package io.renren.modules.substation.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.modules.substation.entity.*;
import io.renren.modules.substation.service.TInfoAreaInfoService;
import io.renren.modules.substation.service.TInfoEfencePointService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.substation.service.TInfoEfenceInfoPService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 电子围栏表
 *
 * @author yzx
 * @email sunlightcs@gmail.com
 * @date 2020-07-16 01:02:15
 */
@RestController
@RequestMapping("substation/tinfoefenceinfop")
public class TInfoEfenceInfoPController {
    @Autowired
    private TInfoEfenceInfoPService tInfoEfenceInfoPService;
    @Autowired
    private TInfoEfencePointService tInfoEfencePointService;
    @Autowired
    private TInfoAreaInfoService tInfoAreaInfoService;
    private static Logger logger = LoggerFactory.getLogger(TInfoBackupConfigController.class);


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("substation:tinfoefenceinfop:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tInfoEfenceInfoPService.queryPage(params);

        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.list();
        List<TInfoEfenceInfoPEntity> list = (List<TInfoEfenceInfoPEntity>)page.getList();
        if(list != null) {
            for(int i=0;i<list.size();i++) {
                if (areaList != null) {
                    for (int j = 0; j < areaList.size(); j++) {
                        if (list.get(i).getDevArea() == areaList.get(j).getAreaId()) {
                            list.get(i).setAreaName(areaList.get(j).getAreaName());
                        }
                    }
                }
            }
        }
        page.setList(list);

//        int a = 6727233;
//        logger.debug("a的值:" + a);
//
//        float b = (float) a;
//
//        logger.debug("b的值:" + b);

        return R.ok().put("page", page);
    }

    /**
     * 关联列表
     */
    @RequestMapping("/listefence/{devCode}")
//    @RequiresPermissions("substation:tinfoefenceinfop:listefence")
    public R listefence(@PathVariable("devCode") String devCode){
//        logger.debug("params:" + params.toString());
//        int page = Integer.parseInt((String)params.get("page"));
//        int limit = Integer.parseInt((String)params.get("limit"));
//        String devCode = (String)params.get("devCode");
        logger.debug("devCode"+devCode);

        TInfoEfenceInfoPShow tInfoEfenceInfoPShow = new TInfoEfenceInfoPShow();
        tInfoEfenceInfoPShow.setDevCode(devCode);

//        tInfoEfenceInfoPShow.setLimit(limit);
//        tInfoEfenceInfoPShow.setPageFlag(1);
//        int startIndex=limit*(page-1);
//        tInfoEfenceInfoPShow.setStartIndex(startIndex>=0?startIndex:0);

        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.list();
//        if(areaList != null){
//            for(int i=0;i<areaList.size();i++){
//                areaList.get(i).getAreaId();
//            }
//        }

//        int total_num= (int)tInfoEfenceInfoPService.queryEfenceListCount(tInfoEfenceInfoPShow);
        List<TInfoEfenceInfoPShow> ret_list=tInfoEfenceInfoPService.queryEfenceShowList(tInfoEfenceInfoPShow);
        for(TInfoEfenceInfoPShow o : ret_list){
            o.setPostPp("p1("+o.getPostX1() +","+ o.getPostY1() + "),p2(" + o.getPostX2() +","+ o.getPostY2()+")");

            if(areaList != null){
                for(int i=0;i<areaList.size();i++){
                    if(o.getDevArea() == areaList.get(i).getAreaId()){
                        o.setAreaName(areaList.get(i).getAreaName());
                    }
                }
            }

        }

//        PageUtils retPageUtil=new PageUtils(ret_list,total_num,limit,page);
//        logger.debug("retPageUtil:"+retPageUtil.toString());
//        logger.debug("retPageUtil:"+retPageUtil.getList().get(1));
        return R.ok().put("list", ret_list);
    }
    /**
     * 关联列表
     */
    @RequestMapping("/listefencePage")
//    @RequiresPermissions("substation:tinfoefenceinfop:listefencePage")
    public R listefencePage(@RequestParam Map<String, Object> params){
//        PageUtils page = tInfoEfenceInfoPService.queryPage(params);

        logger.debug("params:" + params.toString());
        int page = Integer.parseInt((String)params.get("page"));
        int limit = Integer.parseInt((String)params.get("limit"));
        String devCode = (String)params.get("devCode");
        logger.debug("devCode"+devCode);

        TInfoEfenceInfoPShow tInfoEfenceInfoPShow = new TInfoEfenceInfoPShow();
        tInfoEfenceInfoPShow.setDevCode(devCode);

        tInfoEfenceInfoPShow.setLimit(limit);
        tInfoEfenceInfoPShow.setPageFlag(1);
        int startIndex=limit*(page-1);
        tInfoEfenceInfoPShow.setStartIndex(startIndex>=0?startIndex:0);

        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.list();
//        if(areaList != null){
//            for(int i=0;i<areaList.size();i++){
//                areaList.get(i).getAreaId();
//            }
//        }

        int total_num= (int)tInfoEfenceInfoPService.queryEfenceListCount(tInfoEfenceInfoPShow);
        List<TInfoEfenceInfoPShow> ret_list=tInfoEfenceInfoPService.queryEfenceShowListPage(tInfoEfenceInfoPShow);
        for(TInfoEfenceInfoPShow o : ret_list){
            o.setPostPp("p1("+o.getPostX1() +","+ o.getPostY1() + "),p2(" + o.getPostX2() +","+ o.getPostY2()+")");

            if(areaList != null){
                for(int i=0;i<areaList.size();i++){
                    if(o.getDevArea() == areaList.get(i).getAreaId()){
                        o.setAreaName(areaList.get(i).getAreaName());
                    }
                }
            }
        }
        PageUtils retPageUtil=new PageUtils(ret_list,total_num,limit,page);
        logger.debug("retPageUtil:"+retPageUtil.toString());
        logger.debug("retPageUtil:"+retPageUtil.getList().get(1));
        return R.ok().put("page", retPageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{efenceHostId}")
    @RequiresPermissions("substation:tinfoefenceinfop:info")
    public R info(@PathVariable("efenceHostId") Long efenceHostId){
		TInfoEfenceInfoPEntity tInfoEfenceInfoP = tInfoEfenceInfoPService.getById(efenceHostId);
        List<TInfoEfencePointEntity> list = tInfoEfencePointService.getByDevCode(tInfoEfenceInfoP.getDevCode());
        if(list != null) {
            logger.debug("list:" + list);
            JSONArray array = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                JSONObject obj = new JSONObject();
                obj.put("pointId",list.get(i).getEfencePointId());
                obj.put("postCode",list.get(i).getPostCode());
                obj.put("postAddr",list.get(i).getPostAddr());
                obj.put("key",i);
                array.add(obj);
            }
            tInfoEfenceInfoP.setDomains(array);
        }
//        TInfoEfenceInfoPShow tInfoEfenceInfoPShow = new TInfoEfenceInfoPShow();
//        BeanUtils.copyProperties(tInfoEfenceInfoP, tInfoEfenceInfoPShow);
        logger.debug("tInfoEfenceInfoP:" + tInfoEfenceInfoP);
//        logger.debug("tInfoEfenceInfoPShow:" + tInfoEfenceInfoPShow);

        return R.ok().put("tInfoEfenceInfoP", tInfoEfenceInfoP);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("substation:tinfoefenceinfop:save")
    public R save(@RequestBody TInfoEfenceInfoPEntity tInfoEfenceInfoP){


        logger.debug("getPostNumber:"+ tInfoEfenceInfoP.getPostNumber());
        logger.debug("-----tInfoEfenceInfoP----- :"+ tInfoEfenceInfoP);
//        List listDomains = tInfoEfenceInfoP.getDomains();
        JSONArray domainsarray = tInfoEfenceInfoP.getDomains();
        logger.debug("-----domainsarray----- "+ domainsarray +" size:"+ domainsarray.size());
        tInfoEfenceInfoP.setIsVaild("1");
        tInfoEfenceInfoP.setCreateOpr((long)0);
        tInfoEfenceInfoP.setCreateTime(new Date());
        tInfoEfenceInfoP.setLastOpr((long)0);
        tInfoEfenceInfoP.setLastTime(new Date());

        if(domainsarray != null) {
//        String postNumber = tInfoEfenceInfoP.getPostNumber();
//        if(!postNumber.isEmpty() || postNumber != "") {
//            int num = Integer.parseInt(postNumber);
//            if(num < 65 && num > 0){
            if(domainsarray.size() > 0) {
                for (int i = 0; i < domainsarray.size(); i++) {
                    JSONObject domainobj = domainsarray.getJSONObject(i);
                    String postCode = domainobj.getString("postCode");
                    String postAddr = domainobj.getString("postAddr");
                    TInfoEfencePointEntity tInfoEfencePointEntity = new TInfoEfencePointEntity();
                    tInfoEfencePointEntity.setDevCode(tInfoEfenceInfoP.getDevCode());
                    tInfoEfencePointEntity.setPostCode(postCode);
                    tInfoEfencePointEntity.setPostAddr(postAddr);
                    tInfoEfencePointEntity.setCreateOpr((long) 0);
                    tInfoEfencePointEntity.setCreateTime(new Date());
                    tInfoEfencePointEntity.setLastOpr((long) 0);
                    tInfoEfencePointEntity.setLastTime(new Date());
//                    tInfoEfenceInfoP.setPostCode(postCode);
                    tInfoEfencePointService.save(tInfoEfencePointEntity);
                }
                tInfoEfenceInfoPService.save(tInfoEfenceInfoP);
            }
        }
//        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("substation:tinfoefenceinfop:update")
    public R update(@RequestBody TInfoEfenceInfoPEntity tInfoEfenceInfoP){
        TInfoEfenceInfoPEntity tInfoEfenceInfoPEntity = tInfoEfenceInfoPService.getById(tInfoEfenceInfoP.getEfenceHostId());
        List<TInfoEfencePointEntity> list = tInfoEfencePointService.getByDevCode(tInfoEfenceInfoPEntity.getDevCode());
        JSONArray domainsarray = tInfoEfenceInfoP.getDomains();

        if(domainsarray != null) {
            if(list != null) {
                for (int i = 0; i < domainsarray.size(); i++) {
                    int sum = 0;
                    JSONObject obj = domainsarray.getJSONObject(i);
                    String postAddr = obj.getString("postAddr");
                    String postCode = obj.getString("postCode");
                    logger.debug("postAddr:"+postAddr + " postCode:" + postCode);
                    for (int j = 0; j < list.size(); j++) {
                        logger.debug("list.get(j).getPostCode():" + list.get(j).getPostCode() );
                        if (postCode.equals(list.get(j).getPostCode())) {
                            sum++;
                            logger.debug("list.get(j).getPostAddr():"+list.get(j).getPostAddr() );
                            if(!postAddr.equals(list.get(j).getPostAddr())) {
                                TInfoEfencePointEntity tInfoEfencePointEntity = new TInfoEfencePointEntity();
                                tInfoEfencePointEntity.setPostCode(postCode);
                                tInfoEfencePointEntity.setDevCode(tInfoEfenceInfoPEntity.getDevCode());
                                tInfoEfencePointEntity.setPostAddr(postAddr);
                                tInfoEfencePointService.updateByPostCodeAndDevCode(tInfoEfencePointEntity);
                            }
                        }
                    }
                    logger.debug("sum:"+sum );
                    if(sum == 0){
                        TInfoEfencePointEntity tInfoEfencePointEntity = new TInfoEfencePointEntity();
                        tInfoEfencePointEntity.setDevCode(tInfoEfenceInfoPEntity.getDevCode());
                        tInfoEfencePointEntity.setPostCode(postCode);
                        tInfoEfencePointEntity.setPostAddr(postAddr);
                        tInfoEfencePointEntity.setCreateOpr((long) 0);
                        tInfoEfencePointEntity.setCreateTime(new Date());
                        tInfoEfencePointEntity.setLastOpr((long) 0);
                        tInfoEfencePointEntity.setLastTime(new Date());
                        tInfoEfencePointService.save(tInfoEfencePointEntity);
                    }
                }
            } else {

                for (int i = 0; i < domainsarray.size(); i++) {
                    JSONObject obj = domainsarray.getJSONObject(i);
                    String postAddr = obj.getString("postAddr");
                    String postCode = obj.getString("postCode");
                    TInfoEfencePointEntity tInfoEfencePointEntity = new TInfoEfencePointEntity();
                    tInfoEfencePointEntity.setDevCode(tInfoEfenceInfoPEntity.getDevCode());
                    tInfoEfencePointEntity.setPostCode(postCode);
                    tInfoEfencePointEntity.setPostAddr(postAddr);
                    tInfoEfencePointEntity.setCreateOpr((long) 0);
                    tInfoEfencePointEntity.setCreateTime(new Date());
                    tInfoEfencePointEntity.setLastOpr((long) 0);
                    tInfoEfencePointEntity.setLastTime(new Date());

                    logger.debug("save:"+tInfoEfencePointEntity );
                    tInfoEfencePointService.save(tInfoEfencePointEntity);
                }
            }
        }

        logger.debug("updateById:"+tInfoEfenceInfoP );
        tInfoEfenceInfoPService.updateById(tInfoEfenceInfoP);


        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("substation:tinfoefenceinfop:delete")
    public R delete(@RequestBody Long[] efenceHostIds){

        for(int i=0;i<efenceHostIds.length;i++){
            TInfoEfenceInfoPEntity tInfoEfenceInfoPEntity = tInfoEfenceInfoPService.getById(efenceHostIds[i]);
            if(tInfoEfenceInfoPEntity.getDevCode() != null) {
                tInfoEfencePointService.removeBydevCode(tInfoEfenceInfoPEntity.getDevCode());
            }
        }

		tInfoEfenceInfoPService.removeByIds(Arrays.asList(efenceHostIds));
        return R.ok();
    }

    @RequestMapping("/areaDevList")
//    @RequiresPermissions("substation:tinfoefenceinfo:areaDevList")
    public R areaDevList(){
        //查询列表数据
        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.list();

        return R.ok().put("list", areaList);
    }

}
